#!/usr/bin/env python
# encoding: utf-8
"""
DataManager.py

"""
import settings

import os
import cPickle

class Corpus(object):
    """
    working with existing corpora, their indexes and lexicons.
    
    """

    def __init__(self, name):
        """ switch to data folder"""
        self.name = name            # corpus name
        self.meta = {}
    
    def register(self):
        """ register corpora in a dictionary and save it to disk """
        try:
            os.chdir(os.path.join(settings.DATA_PATH))
        except:
            raise EnvironmentError('No data folder found!')
            
        if 'corpora' in os.listdir(os.curdir):
            self.corpora = cPickle.load(open('corpora', 'r'))
            if self.corpora.has_key(self.name):
                raise IOError('Corpus with this name already registered!')
            else:
                self.corpora[self.name] = [] 
            cPickle.dump(self.corpora, open('corpora', 'w'))
        else:
            self.corpora = {self.name : []}
            cPickle.dump(self.corpora, open('corpora', 'w'))
        return
        
    def open(self):
        """ loads meta information about a corpus """
        try:
            
            file = open(os.path.join(settings.DATA_PATH, self.name))
        except:
            raise IOError('No Index with the name %s !' % (self.name))
        self.meta = cPickle.load(file)
        return
    
    def close(self):
        """ return to / """
        try:
            os.chdir(os.path.join('..'))
        except:
            raise EnvironmentError('Could not go up!')
        return
    
    def delete(self):
        """ removes corpus from list and deletes all depending files """
        try:
            self.corpora = cPickle.load(open('corpora', 'r'))
        except:
            raise IOError('No corpora file')
        if self.name in self.corpora:
            del self.corpora[self.name]
            cPickle.dump(self.corpora, open('corpora', 'w'))
            # TODO all actual files with this corpus should be deleted
        else:
            raise IOError('There is no such corpus!')
        return
    
    def get(self, type):
        """ get index or lexicon of a corpus """
        return self.meta[type]
    
    def __str__(self):
        return "You are working with: %s" % (self.name)
	

def listCorpora():
    """ a list of registered corpora """
    return cPickle.load(open(settings.DATA_PATH+'corpora', 'r'))


if __name__ == '__main__':
    print "Registered Corpora: " , listCorpora()